package com.gome.ocean.common.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TreeMap;
import java.util.concurrent.Callable;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gome.framework.util.IoUtil;
import com.gome.ocean.common.constants.DataxContants;
import com.gome.ocean.common.exception.DataxWriterConfException;

/**
 * datax 文件输出工具
 * 
 * @author haqiaolong 2016年1月21日 下午3:03:52
 * @since 5.0.0
 */
public final class DataxHelper {

    private DataxHelper(){
    }

    private static final String DEFAULT_CHATSET = "utf-8";
    private static final Logger LOG             = LoggerFactory.getLogger(RetryUtil.class);
    private static final int    RETRY_TIME      = 3;

    /**
     * 写配置文件默认重试3次
     * 
     * @param data
     * @param fileName
     * @return
     */
    public static boolean WriterConf(final String data, final long fileName) {
        return WriterConf(data, fileName, DEFAULT_CHATSET);

    }

    /**
     * 写配置文件默认重试3次
     * 
     * @param data
     * @param fileName
     * @return
     */
    public static boolean WriterConf(final String data, final long fileName, final String charSet) {
        try {
            return RetryUtil.executeWithRetry(new Callable<Boolean>() {

                @Override
                public Boolean call() throws Exception {
                    OutputStream output = null;
                    try {
                        output = new FileOutputStream(DataxContants.getWriterPath(fileName));
                        IoUtil.write(data, output, charSet);
                        return true;
                    } catch (FileNotFoundException e) {
                        LOG.error("文件找不到！", e);
                        return false;
                    } catch (IOException e) {
                        LOG.error("文件生成错误！", e);
                        return false;
                    } finally {
                        if (output != null) {
                            output.close();
                        }
                    }
                }
            }, RETRY_TIME, 1000L, true);
        } catch (Exception e) {
            throw new DataxWriterConfException("创建配置文件出错,请检查!", e);
        }
    }

    /**
     * 获取最新的一个文件
     * 
     * @param jsonName
     * @return
     */
    public static String getCurrentDataxLogPath(final String jsonName) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(TimeUtils.DEFAULT_FORMAT);
        String currentDate = dateFormat.format(new Date());
        File dir = new File(DataxContants.getDataxLogPath().concat(File.separator).concat(currentDate));
        File[] files = dir.listFiles(new DataxLogNameFilter(jsonName));
        if (files == null) {
            LOG.error("日志文件不存在！请检查！");
            return null;
        } else {
            TreeMap<Long, File> treeMap = new TreeMap<Long, File>();
            for (File file : files) {
                treeMap.put(file.lastModified(), file);
            }
            if (!treeMap.isEmpty()) return treeMap.lastEntry().getValue().getAbsolutePath();
            else return StringUtils.EMPTY;

        }
    }

    /**
     * datax日志名称过滤
     * 
     * @author haqiaolong 2016年1月27日 下午5:13:15
     * @since 5.0.0
     */
    private static class DataxLogNameFilter implements FilenameFilter {

        private String jsonName;

        public DataxLogNameFilter(String jsonName){
            this.jsonName = jsonName;
        }

        @Override
        public boolean accept(File dir, String name) {
            if (name.contains(jsonName)) {
                return true;
            }
            return false;
        }

    }
}
